<script setup>
import { ref } from 'vue'
import { userLogin } from '@/api/index'
import useStore from '@/store'
import { Toast } from 'vant'
import { useRouter } from 'vue-router'
const baseurl = process.env.VUE_APP_URL
const { user } = useStore()
const router = useRouter()
const form = ref({
  loginName: 'admin',
  password: '',
  vcode: ''
})
const rules = {
  loginName: [{ required: true, message: '必填', trigger: 'onChange' }],
  password: [{ required: true, message: '必填', trigger: 'onChange' }],
  vcode: [
    { required: true, message: '必填', trigger: 'onChange' },
    {
      pattern: /^\d{4}$/,
      message: '请输入四位验证码',
      trigger: 'onChange'
    }
  ]
}
const formCom = ref(null)
const submit = async () => {
  await formCom.value.validate()
  const res = await userLogin(form.value)
  user.setToken(res.result.data.token)
  Toast.success('登录成功')
  router.push('/')
  console.log(res)
}
// 验证码点击
const randomNum = ref(0)
const codeClick = () => {
  randomNum.value = Date.now()
}
</script>
<template>
  <div class="login">
    <van-nav-bar title="登录"></van-nav-bar>
    <van-form ref="formCom">
      <van-field
        :rules="rules.loginName"
        v-model="form.loginName"
        placeholder="请输入用户名"
        label="用户名"
      ></van-field>
      <van-field
        :rules="rules.password"
        v-model="form.password"
        placeholder="请输入密码"
        label="密码"
      ></van-field>
      <van-field
        label="验证码"
        placeholder="请输入验证码"
        v-model="form.vcode"
        :rules="rules.vcode"
      >
        <template #button>
          <img
            class="code"
            @click="codeClick"
            :src="baseurl + '/auth/verifyImage?t=' + randomNum"
            alt=""
          />
          <!-- :src="$baseurl + '/user/validate?t=' + randomNum" -->
        </template>
      </van-field>
    </van-form>
    <van-button block @click="submit">登录</van-button>
  </div>
</template>

<style lang="scss" scoped>
.login {
  padding: 20px;
  height: 100vh;
  .code {
    height: 24px;
  }
}
</style>
